import React, { useState, useRef, useEffect } from 'react';
import TauActionPanel from '@/components/TauActionPanel';
import TauPage from '@/components/TauPage';
import TauTable from '@/components/TauTable';
import { t } from '@lingui/macro';
import { Button, Drawer, Message, Checkbox, Dropdown, Menu, Icon } from '@alifd/next';
import { useStore } from '@/hooks';
import { uniqueId } from 'lodash';
import { column, toSelectDataSource, ENUMS } from './stores/definitions';
import { observer } from 'mobx-react-lite';
import { toJS } from 'mobx';
import DataForm from './components/DataForm';
import ComponentsDrawer from '@/components/Drawers/ComponentsDrawer';
import QR from './components/QR';

const tableId = uniqueId('tauTable-');

const Driver = ({ queryParams }) => {
  const { driverStore: store } = useStore();
  const [modal, setModal] = useState([]);
  const driverRef = useRef();
  const [showOrders, setShowOrders] = useState(false);
  const [counts, setCounts] = useState([]);
  const [qr, setQr] = useState({});

  useEffect(() => {
    if (showOrders) {
      (async () => {
        const res = await fetchOrderCounts();
        setCounts(res);
      })();
    } else {
      setCounts([]);
    }
  }, [showOrders, store.driver]);

  async function fetchOrderCounts() {
    const promiseAry = store.driver.map((p) => store.api.ccOrderCount({
      search: {
        driverId: p.id,
      },
    }).then((r) => ({ id: p.id, count: r })));
    return Promise.all(promiseAry);
  }

  /**
   * @description 处理搜索条件
   * @param {*} params
   */
  const handleOnSearch = (params) => {
    const { ...searchArgs } = params.values;
    store.search = {
      ...queryParams,
      ...searchArgs,
    };
  };

  /**
   * @description 修改司机
   */
  const handleOpenEdit = (r) => {
    driverRef.current = r;
    setModal(['edit']);
  };

  /**
   * @description 添加司机
   */
  const handleOpenAdd = () => {
    driverRef.current = {};
    setModal(['add']);
  };

  /**
   * 修政司机
   * @param {*} result
   */
  const handleUpdate = async (result) => {
    if (!_.isEmpty(result)) {
      try {
        await store.update(toJS(result));
        Message.success({ content: t`修政成功` });
      } catch (e) {
        Message.error({ content: t`修政失败`, duration: 7000 });
        throw e;
      }
    }
    setModal([]);
  };

  /**
   * 新增司机
   * @param {*} result
   */
  const handleCreate = async (result) => {
    if (!_.isEmpty(result)) {
      try {
        result.accountId = result.mobile;
        await store.create(toJS(result));
        Message.success({ content: t`创建成功` });
      } catch (e) {
        Message.error({ content: t`创建失败`, duration: 7000 });
        throw e;
      }
    }
    setModal([]);
  };

  /**
   * @description 查看司机
   * @param {*} r
   */
  const handleOpenCheck = (r) => {
    driverRef.current = r;
    setModal(['view']);
  };

  /**
   * @description 关闭modal
   */
  const handleCancel = () => {
    setModal([]);
  };

  /**
   * 查看包车订单
   */
  const handleOpenVehicle = (r) => {
    driverRef.current = r;
    setModal(['ccOrder']);
  };

  // 打开二维码
  const handelOpenQR = async (result) => {
    try {
      const { fullname, username } = result;
      // const baseUrl = await store.getURL(username);
      setQr({
        ...qr,
        open: true,
        okText: '下载',
        onCancel: CROnCancel,
        name: fullname,
        username,
      });
    } catch (error) {
      console.log('🚀 _ file: index.jsx:147 _ error:', error);
    }
  };

  const CROnCancel = () => {
    setQr({ open: false });
  };

  return (
    <TauPage className="page-container">
      <TauActionPanel
        onSearch={handleOnSearch}
        actions={[
          {
            name: 'btn-addDriver',
            title: t`添加司机`,
            type: 'primary',
            onClick: handleOpenAdd,
          },
        ]}
        searchItems={[
          {
            name: 'dutyStatus',
            type: 'select',
            props: {
              dataSource: toSelectDataSource(ENUMS.dutyStatus),
              placeholder: t`值班状态`,
            },
          },
          {
            name: 'driverStatus',
            type: 'select',
            props: {
              dataSource: toSelectDataSource(ENUMS.driverStatus),
              placeholder: t`启用状态`,
            },
          },
        ]}
        extraItems={[
          {
            name: 'cbx-showOrders',
            component: <Checkbox style={{ marginLeft: 10 }} onChange={(v) => setShowOrders(v)}>{t`查看订单`}</Checkbox>,
          },
        ]}
        keywordSearch={{
          // enabled: false,
          placeholder: t`请输入关键字搜搜`,
        }}
        className="action-panel"
      />
      <div className="content">
        <TauTable
          instanceId={tableId}
          primaryKey="id"
          tableLayout="fixed"
          currentPage={store.pg.page}
          pageSize={store.pg.size}
          total={store.total}
          onFetch={(pg) => { store.pg = pg; }}
          loading={store.loading}
          dataSource={toJS(store.driver)}
          columns={[
            { title: t`编号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.idx(i) },
            column('company.name', { width: 88 }),
            column('fullname', { width: 88 }),
            column('gender', { width: 88 }),
            column('driverInfo.dateBirth', { width: 88 }),
            column('vehicle.permanentLandName', { width: 88 }),
            column('mobile', { width: 88 }),
            column('commentStarSum', { width: 88 }),
          ].concat(global.isAdmin ? [column('counters.ccorder', { width: 88, cell: (v, _, r) => <Button type="primary" text onClick={() => handleOpenVehicle(r)}>{counts.find((p) => p.id === r.id)?.count || 0}</Button> }),
          ] : []).concat([
            column('driverInfo.dutyStatus', { width: 98 }),
            column('vehicle.driverInfo.dutyVehicleId', {
              width: 88,
              cell: (v, _, r) => {
                const { vehicle = {} } = r;
                return (
                  <>
                    <span>{vehicle?.licenseNo?.mainland || ''}</span>
                    <br />
                    <span>{vehicle?.licenseNo?.hk || ''}</span>
                  </>);
              },
            }),
            column('driverInfo.driverStatus', { width: 88 }),
            {
              title: t`操作`,
              dataIndex: 'dispatchNumber',
              width: 220,
              cell: (_, __, driver) => (
                <>
                  <Button text type="primary" onClick={() => handleOpenEdit(driver)} >{t`编辑`}</Button>
                  <span style={{ color: 'var(--btn-text-primary-color, #5584FF)' }}> | </span>
                  <Button text type="primary" onClick={() => handelOpenQR(driver)} >{t`二维码`}</Button>
                  <span style={{ color: 'var(--btn-text-primary-color, #5584FF)' }}> | </span>
                  <Dropdown
                    trigger={<a style={{ color: '#5584FF', cursor: 'pointer' }}>更多 <Icon type="arrow-down" size="xs" /></a>}
                    triggerType={['hover', 'click']}
                  >
                    <Menu>
                      <Menu.Item key={'1'}><Button text type="primary" onClick={() => handleOpenEdit(driver)} >{t`排班`}</Button></Menu.Item>
                      <Menu.Item key={'2'}><Button text type="primary" onClick={() => handleOpenCheck(driver)} >{t`查看`}</Button></Menu.Item>
                    </Menu>
                  </Dropdown>
                </>),
            }]).filter((c) => c.dataIndex !== 'counters.ccorder' || showOrders)}
        />
      </div>
      <Drawer
        visible={modal[0] === 'add' || modal[0] === 'view' || modal[0] === 'edit'}
        // eslint-disable-next-line no-nested-ternary
        title={modal[0] === 'view' ? '查看司机' : (modal[0] === 'add' ? '添加司机' : '编辑司机')}
        style={{ maxWidth: '90%' }}
        closeMode={['esc', 'mask', 'close']}
        onClose={() => setModal([...modal, `toClose$${Date.now()}`])}
        width="90%"
      >
        <DataForm
          id={driverRef.current?.id}
          modal={modal}
          onCancel={() => handleCancel()}
          onSubmit={modal[0] === 'add' ? handleCreate : handleUpdate}
        />
      </Drawer>
      <ComponentsDrawer
        modal={modal}
        name={driverRef.current?.fullname}
        queryParams={{ driverId: driverRef.current?.id }}
        onCancel={handleCancel}
      />
      <QR modal={qr} />
    </TauPage>
  );
};

export default observer(Driver);
